<?php
/**
 * 忽略权限类
 *
 * PHP Version 5.6
 *
 * @author    guanxu <510104561@qq.com>
 * @time      2017/08/11
 */
namespace Admin\Controller;

include(__DIR__.'/../../../vendor/gregwar/captcha/CaptchaBuilderInterface.php');
include(__DIR__.'/../../../vendor/gregwar/captcha/PhraseBuilderInterface.php');
include(__DIR__.'/../../../vendor/gregwar/captcha/CaptchaBuilder.php');
include(__DIR__.'/../../../vendor/gregwar/captcha/PhraseBuilder.php');

use Think\Controller;
use Gregwar\Captcha\CaptchaBuilder;
use Common\Common\ConstantUtil;


class IndexController extends Controller {

    /**
     * 登陆页
     */
    public function login() {
        session('admin_user',null);
        $this->display("login/login");
    }

    /**
     * 登陆处理页
     */
    public function logined() {
        $username = I("post.username");
        $password = I("post.password");
        $validCode = session("validCode");
        if(empty($username)) $this->error('用户名为空!', 'login/login');
        if(empty($password)) $this->error('密码为空!', 'login/login');
        if(empty($validCode)) $this->error('验证码获取失败!', 'login/login');
        $result = M("user")->where([
            "username"  => $username,
            "password"  => md5($password),
            "status"    => ConstantUtil::GLOBAL_TRUE,
            "rank"      => ["ELT",ConstantUtil::POWER_MANAGE]
        ])->find();
        if(empty($result)) $this->error('用户名或密码错误!', 'login/login');
        session("admin_user",$result);
        $this->header();
        $this->success('登陆成功!', 'index');
    }

    /**
     * 获取所有模块并且更新session
     * @return bool
     */
    public function header() {
        $user = session("admin_user");
        if(empty($user)) return false;
        $modules = $this->getModules($user["id"]);
        session("admin_modules",$modules);
        return true;
    }

    /**
     * 获取模块
     * @param $user_id
     * @return array|bool
     */
    private function getModules($user_id) {

        $rank = M("user")->where(["id"=>$user_id])->getField("rank");
        // 判断是否超级管理员   是给予全部权限
        if($rank != ConstantUtil::POWER_SUPER_MANAGE) return $this->userPower($user_id);
        $result = [];
        $sys_column = M("sys_column")->where(["status"=>ConstantUtil::GLOBAL_TRUE])->select();
        foreach($sys_column as $val ) {
            $classify = M("classify")->where(["sys_column_id"=>$val["id"],"status"=>ConstantUtil::GLOBAL_TRUE,"classify"=>ConstantUtil::SYSTEM_ADMIN])->select();
            $val["list"] = $classify;
            $result[$val["id"]] = $val;
        }
        foreach($result as  $key => $val) {
            $result[$key]["list"] = "";
            foreach($val["list"] as $val2) {
                $modules = M("modules")->where(["classify_id"=>$val2["id"],"status"=>ConstantUtil::GLOBAL_TRUE])->select();
                $val2["list"] = $modules;
                $result[$key]["list"][] = $val2;
            }
        }
        return [
            "modules" => $result
        ];

    }


    /**
     * 获取用户权限
     * @param $user_id
     * @return array|bool
     */
    private function userPower($user_id) {
        if(empty($user_id)) return false;
        $result = $modules = $modules_list = $return = [];
        // 获取对应角色
        $role_user = M("role_user")->where(["user_id"=>$user_id])->select();
        // 获取角色对应的权限
        foreach($role_user as $val) {
            $role_relation      = M("role_relation")->where(["role_id"=>$val["role_id"]])->getField("modules_func_id",true);
            if(empty($role_relation)) continue;
            $modules_id         = M("modules_func")->where(["id"=>["IN",$role_relation],"status"=>ConstantUtil::GLOBAL_TRUE])->distinct(true)->getField("modules_id",true);
            $modules_function  = M("modules")->where(["id"=>["IN",$modules_id],"status"=>ConstantUtil::GLOBAL_TRUE])->getField("url",true);
            //var_dump($modules_function);
            foreach($modules_function as $val2) {
                $url = $this->urlManage($val2);
                if(empty($url)) continue;
                $result["function"][] = U($url);
            }
            $function   = M("modules_func")->where(["id"=>["IN",$role_relation]])->getField("url",true);
            foreach($function as $val2) {
                $url = $this->urlManage($val2);
                if(empty($url)) continue;
                $result["function"][] =  U($url);
            }
            $modules_list[] = $modules_id;
        }
        // 优化权限结构
        foreach($modules_list as $val) {
            foreach($val as $val2) {
                if(!in_array($val2,$modules)) $modules[] = $val2;
            }
        }

        if(empty($modules)) return false;
        $list = M("modules")
            ->join("left join classify  on classify.id = modules.classify_id")
            ->join("left join sys_column  on sys_column.id = classify.sys_column_id")
            ->where(["modules.id"=>["IN",$modules],"modules.status"=>ConstantUtil::GLOBAL_TRUE])
            ->field("modules.*,classify.name as classify_name,sys_column.id as sys_column_id ,sys_column.name as sys_column_name")
            ->select();
        // 编辑结果
        foreach($list as $val) {
            // 一级栏目
            $sys_column = [];
            // 二级栏目
            $classify   = [];
            $classify["id"]                             = $val["classify_id"];
            $classify["name"]                           = $val["classify_name"];
            $classify["list"][]                         = $val;
            $sys_column["id"]                           = $val["sys_column_id"];
            $sys_column["name"]                         = $val["sys_column_name"];
            $sys_column["list"][$val["classify_id"]]    = $classify;
            // 如果已经有一级栏目则只增加二级栏目
            if(!empty($return[$val["sys_column_id"]])) {
                // 如果已经有二级栏目只增加三级栏目
                if(!empty( $return[$val["sys_column_id"]]["list"][$val["classify_id"]]) ) {
                    $return[$val["sys_column_id"]]["list"][$val["classify_id"]]["list"][] = $val;
                }else{
                    $return[$val["sys_column_id"]]["list"][$val["classify_id"]] = $classify;
                }
                //$return[$val["sys_column_id"]]["list"][$val["classify_id"]][] = $val;
            } else {
                $return[$val["sys_column_id"]] = $sys_column;
            }
        }
        $result["modules"] = $return;
        return $result;
    }


    public function urlManage($url) {
        if(!strstr($url,"@")) return false;
        $url = explode("@",$url);
        return $url[0].'/'.$url[1];
    }

    /**
     * 验证码获取
     */
    public function captcha() {
        $builder = new CaptchaBuilder();
        $builder->build($width = 100, $height = 40, $font = null);          //可以设置图片宽高及字体
        $phrase = $builder->getPhrase();                                    //获取验证码的内容\
        session('validCode',$phrase);
        header("Cache-Control: no-cache, must-revalidate");                 //生成图片
        header('Content-Type: image/jpeg');
        $builder->output();

    }

    public function index() {
        $this->display("index/index");
    }

    public function quit() {
        session('admin_user',null);
        $this->success("退出成功","login/login");
    }

}